import './app.global';
import {vueMap, vmMap} from './app.vue';
import './app.com';

// console.log(vueMap);
// var a = 1;
Template7.global = {
	version: '实验版V0.0.0'
};

window.$ = Dom7;
// Initialize app
window.myApp = new Framework7({
	pushState: true,
	swipePanel: 'right',
	material: true,
	modalTitle: 'System',
	// fastClicks: true,
	// uniqueHistory: true,
	template7Pages: true
});

/* Initialize views */
window.mainView = myApp.addView('.view-main', {
	// dynamicNavbar: false,
	preloadPreviousPage: true
});
// window.friendsView = myApp.addView('.view-friends', {
//	 // dynamicNavbar: false,
//	 preloadPreviousPage: true
// });
// window.otherView = myApp.addView('.view-other', {
//	 // dynamicNavbar: false,
//	 preloadPreviousPage: true
// });

// console.log(myApp);
myApp.onPageBeforeInit('*', (page) => {
	// console.log(page)
	if (page.name) {
		let vue = vueMap.get(page.name);
		// console.log(vueMap)
		if (vue) {
			let vm = vue.init(page);
			vmMap.set(page.name, vm);
		}
	}
});

/*myApp.onPageInit('*', (page) => {

});
myApp.onPageReinit('*', (page) => {
	// console.log('reinit=>', page);
});
myApp.onPageBeforeAnimation('*', (page) => {
	// console.log('page=>', page);
});*/
// may not need
myApp.onPageBeforeRemove('*', (page) => {
	// console.log(page);
	if (page.name) {
		// console.log('before remove', vmMap.size)
		let vm = vmMap.get(page.name);
		// console.log(vm)
		if (vm) {
			vm.$destroy(true);
			vmMap.delete(page.name);
		}

		// console.log('after removed', vmMap.size)
	}
});

// mainView.router.reloadPage('views/other/top/top.html');
mainView.router.reloadPage('views/start/login/login.html');

/*
* Http post
*/
var md5 = require('./lib/md5.min');
var apiKey = 'darwin_api_key_v1.0';
var APIS = CONFIG.APIS;
window.http = {
	post: function(api, data = {}, auth = true) {
		return new Promise(function(resolve, reject) {
			let url = `${CONFIG.API_BASE_URL}/darwin_${api}.do`;
			if (auth) {
				let userId = localStorage.getItem('userId')||'';
				data['userId'] = userId;
				data['authCd'] = md5(`DARWIN_API_${APIS[api]}:${userId}:${apiKey}`);
				data['token'] = localStorage.getItem('token')||'';
			}
			data['uuid'] = 0;

			$.ajax({
				url: url,
				async: true,
				method: "POST",
				cache: true,
				contentType: "application/x-www-form-urlencoded",
				crossDomain: undefined,
				data: data,
				processData: true,
				dataType: "json",
				// headers: 
				// xhrFields: 
				// username: 
				// password: 
				timeout: 30000,

				beforeSend: function(xhr) {
					myApp.showIndicator();
				},
				success: function(data, status, xhr) {
					resolve(data, status, xhr);
				},
				error: function(xhr, status) {
					reject(status, xhr);
				},
				complete: function (xhr, status) {
					myApp.hideIndicator();
				},
				statusCode: {
					404: function (xhr) {
						console.log('page not found');
					}
				}
			});
		});
	}
};